package service

import (
	"errors"
	"gorm.io/gorm"
	"time"
	"vrcm/src/vrcm/app/admin/models/subject"
	"vrcm/src/vrcm/common/service"

	"vrcm/src/vrcm/app/admin/service/dto/subject"
	"vrcm/src/vrcm/common/actions"
	cDto "vrcm/src/vrcm/common/dto"
)

type EventPaper struct {
	service.Service
}

// GetPage 获取EventPaper列表
func (e *EventPaper) GetPage(c *dto.EventPaperGetPageReq, p *actions.DataPermission, list *[]subject.EventPaper, count *int64) error {
	var err error
	var data subject.EventPaper

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("EventPaperService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取EventPaper对象
func (e *EventPaper) Get(d *dto.EventPaperGetReq, p *actions.DataPermission, model *subject.EventPaper) error {
	var data subject.EventPaper

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetEventPaper error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// GetByEventId 获取EventPaper对象
func (e *EventPaper) GetByEventId(d *dto.EventPaperGetReq) ([]subject.EventPaperDetail, error) {
	var data []subject.EventPaperDetail

	db := e.Orm.Model(&subject.EventPaper{}).
		Distinct("event_paper.paper_id,paper.paper_name").
		Select("event_paper.event_id,event_paper.paper_id,paper.paper_name,paper.start_time,paper.end_time").
		Where("event_paper.tenant_id = ? and event_paper.event_id in ? and paper.is_delete = 2", d.TenantId, d.EventIds)
	if d.EventType > 0 {
		db.Where("event_paper.event_type=?", d.EventType)
	}
	err := db.Joins("left join paper on paper.id = event_paper.paper_id").Find(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return data, err
	}
	return data, nil
}

// Insert 创建EventPaper对象
func (e *EventPaper) Insert(c *dto.EventPaperMultiInsertReq) error {
	var err error
	var data []subject.EventPaper
	c.Generate(&data)

	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			e.Log.Errorf("EventPaperService delete error:%s \r\n", err)
		}
	}()
	//先删除活动试卷关系
	err = tx.Where(&subject.EventPaper{EventId: c.EventId, TenantId: c.TenantId}).Delete(&subject.EventPaper{}).Error
	if err != nil {
		e.Log.Errorf("EventPaperService delete error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//在插入活动试卷关系
	if len(c.PaperIds) <= 0 {
		tx.Rollback()
		return nil
	}
	err = tx.Create(&data).Error
	if err != nil {
		e.Log.Errorf("EventPaperService Insert error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// Update 修改EventPaper对象
func (e *EventPaper) Update(c *dto.EventPaperUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = subject.EventPaper{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("EventPaperService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除EventPaper
func (e *EventPaper) Remove(d *dto.EventPaperDeleteReq, p *actions.DataPermission) error {
	var data subject.EventPaper

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveEventPaper error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

func (e *EventPaper) Enable(d *dto.EventPaperEnableReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	err := tx.Model(&subject.EventPaper{}).Where("event_id = ? and paper_id= ? and tenant_id =?", d.EventId, d.PaperId, d.TenantId).Update("is_enable", d.IsEnable).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("EventPaperService Enable error:%s \r\n", err)
		return err
	}
	if d.IsEnable == 1 {
		param := make(map[string]interface{})
		param["is_enable"] = 2
		param["update_time"] = time.Now().Unix()
		err = tx.Model(&subject.EventPaper{}).Where("event_id = ? and paper_id != ? and tenant_id =?", d.EventId, d.PaperId, d.TenantId).Updates(param).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("EventPaperService Enable error:%s \r\n", err)
			return err
		}
	}

	tx.Commit()
	return nil
}
